package mymgo

import (
	"strconv"
	"sync"

	"lottery/libs/myredis"

	"github.com/astaxie/beego/logs"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"gopkg.in/redis.v5"
)

// ID自增，丢到redis中

type AutoIncr struct {
	prefix string
	colls  []string
	once   *sync.Once
	client *redis.Client
}

func NewAutoIncr(colls []string) (inc *AutoIncr, err error) {
	cli, err := myredis.OpenBase()
	if err != nil {
		return
	}

	inc = &AutoIncr{
		prefix: "mongo_id_",
		client: cli,
		colls:  colls,
		once:   new(sync.Once),
	}
	return
}

func (a *AutoIncr) initInc() {
	sess, err := OpenBase()
	if err != nil {
		panic(err)
	}

	for _, coll := range a.colls {
		collEntity := &struct {
			Id int64 `bson:"_id"`
		}{}
		err := sess.WithC(coll, func(col *mgo.Collection) error {
			return col.Find(bson.M{}).Sort("-_id").One(&collEntity)
		})

		var id int64
		if err != nil {
			if err == mgo.ErrNotFound {
				id = 0
			} else {
				panic(err)
			}
		} else {
			id = collEntity.Id
		}

		if status := a.client.Set(a.getKey(coll), strconv.FormatInt(id, 10), -1); status.Err() != nil {
			logs.Error("设置 %s 初始key出错 %s", coll, status.Err().Error())
			panic(status.Err())
		}
	}
}

func (a *AutoIncr) getKey(name string) string {
	return a.prefix + name
}

func (a *AutoIncr) Contain(name string) bool {
	for _, coll := range a.colls {
		if coll == name {
			return true
		}
	}
	return false
}

func (a *AutoIncr) Inc(coll string) (id int) {
	a.once.Do(a.initInc)

	intCmd := a.client.Incr(a.getKey(coll))
	if intCmd.Err() != nil {
		panic(intCmd.Err())
	}

	id = int(intCmd.Val())
	return
}
